<?php
class omeanalysts_mdl_ome_shop extends dbeav_model{
    public function get_reship($filter=null){
        $sql = 'SELECT count(*) as num FROM '.
            kernel::database()->prefix.'ome_reship WHERE status=\'succ\' and '.$this->_rFilter($filter);

        $row = $this->db->select($sql);
        return $row[0];
    }
    
    public function get_order($filter=null){
        $sql = 'SELECT count(*) as num,sum(total_amount) as amount FROM '.
            kernel::database()->prefix.'ome_orders WHERE is_fail=\'false\' and '.$this->_filter($filter);

        $row = $this->db->select($sql);
        return $row[0];
    }

    public function count($filter=null){
        $date_range = array();
        if(isset($filter['report']) && $filter['report']=='month'){
            $filter['time_from'] = strtotime($filter['time_from']);
            $filter['time_to'] = strtotime($filter['time_to']);
            for($i=$filter['time_from']; $i<=$filter['time_to'];){
                $date_range[] = date("Y-m", $i);
                $i = mktime(0, 0, 0, date('m',$i)+1, date('d',$i), date('Y',$i));
            }
        }else{
            $filter['time_from'] = strtotime($filter['time_from']);
            $filter['time_to'] = (strtotime($filter['time_to'])+86400);
            for($i=$filter['time_from']; $i<$filter['time_to']; $i+=86400){
                $date_range[] = date("Y-m-d", $i);
            }
        }
        return count($date_range);
    }

    public function getlist($cols='*', $filter=array(), $offset=0, $limit=-1, $orderType=null){
        if($filter['type_id']){
            $typeObj = &app::get('omeanalysts')->model('ome_type');
            $flagList = $typeObj->get_shop();
            foreach($flagList as $key=>$val){
                if($filter['type_id']==$val['type_id']){
                    $flag = $val;
                }
            }
        }else{
            $flag['relate_id'] = 0;
            $flag['name'] = '所有店铺';
        }
        $date_range = array();
        if(isset($filter['report']) && $filter['report']=='month'){
            $filter['time_from'] = strtotime($filter['time_from']);
            $filter['time_to'] = strtotime($filter['time_to']);
            for($i=$filter['time_from']; $i<=$filter['time_to'];){
                $date_range[] = date("Y-m", $i);
                $i = mktime(0, 0, 0, date('m',$i)+1, date('d',$i), date('Y',$i));
            }
        }else{
            $filter['time_from'] = strtotime($filter['time_from']);
            $filter['time_to'] = (strtotime($filter['time_to'])+86400);
            for($i=$filter['time_from']; $i<$filter['time_to']; $i+=86400){
                $date_range[] = date("Y-m-d", $i);
            }
        }
        if($orderType == 'time desc'){
            $date_range = array_reverse($date_range);
        }
        if($limit > 0){
            $date_range = array_slice($date_range, $offset, $limit);  
        }
        $analysis_info = app::get('ectools')->model('analysis')->select()->columns('*')->where('service = ?', 'omeanalysts_ome_shop')->instance()->fetch_row();

        if(isset($filter['report']) && $filter['report']=='month'){
            foreach($date_range AS $k=>$date){
                $time_from = strtotime($date.'-01');
                $time_to = mktime(0, 0, 0, date('m',$time_from)+1, date('d',$time_from), date('Y',$time_from));

                if($analysis_info){
                    $obj = app::get('ectools')->model('analysis_logs')->select()->columns('target, sum(value) AS value,time')->where('analysis_id = ?', $analysis_info['id']);
                    $obj->where('time >= ?', $time_from);
                    $obj->where('time < ?', $time_to);
                    if(isset($this->_params['type'])) $obj->where('type = ?', $params['type']);
                    $rows = $obj->where('flag = ?', $flag['relate_id'])->group(array('target'))->instance()->fetch_all();
                    foreach($rows AS $row){
                        $tmp[$date][$row['target']] = $row['value'];
                    }
                }

                $data[$k] = array(
                    'time' => $date,
                    'shop_name'=>$flag['name'],
                    'new_order'=>($tmp[$date][1])?$tmp[$date][1]:0,
                    'pay_order'=>($tmp[$date][2])?$tmp[$date][2]:0,
                    'delivery_order'=>($tmp[$date][3])?$tmp[$date][3]:0,
                    'reship_order'=>($tmp[$date][4])?$tmp[$date][4]:0,
                    'sale_amount'=>($tmp[$date][5])?$tmp[$date][5]:0,
                    'reship_ratio'=>($tmp[$date][6])?$tmp[$date][6]:0,
               );
            }
        }else{
            if($analysis_info){
                $obj = app::get('ectools')->model('analysis_logs')->select()->columns('*')->where('analysis_id = ?', $analysis_info['id']);
                $obj->where('time >= ?', $filter['time_from']);
                $obj->where('time < ?', $filter['time_to']);
                if(isset($this->_params['type'])) $obj->where('type = ?', $params['type']);
                $rows = $obj->where('flag = ?', $flag['relate_id'])->instance()->fetch_all();
                foreach($rows AS $row){
                    $date = date('Y-m-d', $row['time']);
                    $tmp[$date][$row['target']] = $row['value'];
                }
            }
            foreach($date_range AS $k=>$date){
                $data[$k] = array(
                    'time' => $date,
                    'shop_name'=>$flag['name'],
                    'new_order'=>($tmp[$date][1])?$tmp[$date][1]:0,
                    'pay_order'=>($tmp[$date][2])?$tmp[$date][2]:0,
                    'delivery_order'=>($tmp[$date][3])?$tmp[$date][3]:0,
                    'reship_order'=>($tmp[$date][4])?$tmp[$date][4]:0,
                    'sale_amount'=>($tmp[$date][5])?$tmp[$date][5]:0,
                    'reship_ratio'=>($tmp[$date][6])?$tmp[$date][6]:0,
               );
            }
        }

        $this->tidy_data($data, $cols);
        return $data;
    }

    public function _filter($filter,$tableAlias=null,$baseWhere=null){
        $config = app::get('ectools')->getConf('analysis_config');
        $filter['order_status'] = $config['filter']['order_status'];
        $where = array(1);
        if(isset($filter['time_from']) && $filter['time_from']){
            $where[] = ' createtime >='.strtotime($filter['time_from']);
        }
        if(isset($filter['time_to']) && $filter['time_to']){
            $where[] = ' createtime <'.(strtotime($filter['time_to'])+86400);
        }
        if(isset($filter['pay_status']) && $filter['pay_status']){
            $where[] = ' pay_status =\''.$filter['pay_status'].'\'';
        }
        if(isset($filter['ship_status']) && $filter['ship_status']){
            $where[] = ' ship_status =\''.$filter['ship_status'].'\'';
        }
        if(isset($filter['type_id']) && $filter['type_id']){
            $where[] = ' shop_id =\''.$filter['type_id'].'\'';
        }
        if(isset($filter['order_status']) && $filter['order_status']){
            if($filter['order_status']=='confirmed'){
                $where[] = ' process_status != \'unconfirmed\'';
                $where[] = ' process_status != \'cancel\'';
            }
            if($filter['order_status']=='pay'){
                $where[] = ' pay_status IN (\'1\',\'3\',\'4\')';
            }
            if($filter['order_status']=='ship'){
                $where[] = ' ship_status IN (\'1\',\'2\',\'3\')';
            }
        }
        return implode($where,' AND ');
    }

    public function _rFilter($filter,$tableAlias=null,$baseWhere=null){
        $where = array(1);
        if(isset($filter['time_from']) && $filter['time_from']){
            $where[] = ' t_end >='.strtotime($filter['time_from']);
        }
        if(isset($filter['time_to']) && $filter['time_to']){
            $where[] = ' t_end <'.(strtotime($filter['time_to'])+86400);
        }
        if(isset($filter['type_id']) && $filter['type_id']){
            $where[] = ' shop_id =\''.$filter['type_id'].'\'';
        }
        return implode($where,' AND ');
    }

    public function get_schema(){
        $schema = array (
            'columns' => array (
                'time' => array (
                    'type' => 'varchar(200)',
                    'pkey' => true,
                    'label' => '日期',
                    'width' => 90,
                    'editable' => false,
                    'in_list' => true,
                    'default_in_list' => true,
                    'realtype' => 'mediumint(8) unsigned',
                ),
                'shop_name' => array (
                    'label' => app::get('omeanalysts')->_( '店铺'),
                    'width' => 130,
                    'editable' => false,
                    'filtertype' => 'yes',
                    'filterdefault' => true,
                    'in_list' => true,
                ),
                'new_order' => array (
                    'type' => 'number',
                    'label' => '新增订单量',
                    'width' => 75,
                    'editable' => true,
                    'filtertype' => 'normal',
                    'filterdefault' => 'true',
                    'in_list' => true,
                    'is_title' => true,
                    'default_in_list' => true,
                    'realtype' => 'varchar(50)',
                    'orderby' => false,
                ),
                'pay_order' => array (
                    'type' => 'number',
                    'label' => '付款订单量',
                    'width' => 75,
                    'editable' => true,
                    'filtertype' => 'normal',
                    'filterdefault' => 'true',
                    'in_list' => true,
                    'is_title' => true,
                    'default_in_list' => true,
                    'realtype' => 'varchar(50)',
                    'orderby' => false,
                ),
                'delivery_order' => array (
                    'type' => 'number',
                    'label' => '发货订单量',
                    'width' => 75,
                    'editable' => true,
                    'filtertype' => 'normal',
                    'filterdefault' => 'true',
                    'in_list' => true,
                    'is_title' => true,
                    'default_in_list' => true,
                    'realtype' => 'varchar(50)',
                    'orderby' => false,
                ),
                'reship_order' => array (
                    'type' => 'number',
                    'label' => '退换货订单量',
                    'width' => 85,
                    'editable' => true,
                    'filtertype' => 'normal',
                    'filterdefault' => 'true',
                    'in_list' => true,
                    'is_title' => true,
                    'default_in_list' => true,
                    'realtype' => 'varchar(50)',
                    'orderby' => false,
                ),
                'sale_amount' => array (
                    'type' => 'money',
                    'default' => 0,
                    'required' => true,
                    'label' => '订单销售额',
                    'width' => 80,
                    'editable' => false,
                    'filtertype' => 'number',
                    'in_list' => true,
                    'default_in_list' => true,
                    'realtype' => 'mediumint(8) unsigned',
                    'orderby' => false,
                ),
                'reship_ratio' => array (
                    'type' => 'number',
                    'default' => 0,
                    'label' => '订单退货率',
                    'width' => 75,
                    'editable' => false,
                    'hidden' => true,
                    'in_list' => true,
                    'default_in_list' => true,
                    'realtype' => 'mediumint(8) unsigned',
                    'orderby' => false,
                ),
            ),
            'idColumn' => 'time',
            'in_list' => array (
                0 => 'time',
                1 => 'shop_name',
                2 => 'new_order',
                3 => 'pay_order',
                4 => 'delivery_order',
                5 => 'reship_order',
                6 => 'sale_amount',
                7 => 'reship_ratio',
            ),
            'default_in_list' => array (
                0 => 'time',
                1 => 'shop_name',
                2 => 'new_order',
                3 => 'pay_order',
                4 => 'delivery_order',
                5 => 'reship_order',
                6 => 'sale_amount',
                7 => 'reship_ratio',
            ),
        );
        return $schema;
    }
}